package top.truism.practice;

import java.util.Scanner;

public class IpValid {

    public static void main(String[] args) {
        System.out.println("----请输入IP地址：------");
        Scanner scanner = new Scanner(System.in);
        String ip = scanner.nextLine().trim();
        System.out.println("输入的IP地址是：" + ip);
        System.out.println(isValidIp(ip));

    }

    /**
     * 判断IP地址的有效性
     * @param ip
     * @return
     */
    private static boolean isValidIp(String ip) {
        if(ip == null) {
            return false;
        }
        String[] strArr = ip.split("\\.");
        if(strArr.length != 4) {
            return false;
        }
        for (String str : strArr) {
            return isValidIpNormal(str);
        }

        return true;

    }

    private static boolean isValidIpNormal(String str) {
        if(str.length() < 1 || str.length() > 3) {
            return false;
        }
        if(str.startsWith("0") && str.length() > 1) {
            return false;
        }
        try {
            int s = Integer.parseInt(str);
            if(s > 255) {
                return false;
            }
        }catch (ClassCastException e) {
            return false;
        }

        return true;
    }

}
